<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="订单号" prop="orderId">
        <el-input
          v-model="queryParams.orderId"
          placeholder="请输入订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="支付状态" prop="paymentStatus">
        <el-select v-model="queryParams.paymentStatus" placeholder="请选择" clearable>
          <el-option label="待支付" :value="0" />
          <el-option label="已支付" :value="1" />
          <el-option label="已关闭" :value="2" />
          <el-option label="已退款" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="支付平台" prop="paymentPlatform">
        <el-select v-model="queryParams.paymentPlatform" placeholder="请选择平台" clearable>
          <el-option label="支付宝" value="alipay" />
          <el-option label="微信支付" value="wechat" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createdAt">
        <el-date-picker clearable
          v-model="queryParams.createdAt"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:paymentOrders:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:paymentOrders:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:paymentOrders:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:paymentOrders:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="paymentOrdersList" 
      @selection-change="handleSelectionChange"
      stripe
      border
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单号" align="center" prop="orderId" min-width="180" show-overflow-tooltip />
      <el-table-column label="用户ID" align="center" prop="userId" width="100" />
      <el-table-column label="订单标题" align="center" prop="orderTitle" min-width="150" show-overflow-tooltip />
      <el-table-column label="金额/积分" align="center" width="120">
        <template slot-scope="scope">
          <div>
            <div style="color: #f56c6c; font-weight: bold;">¥{{ scope.row.amount }}</div>
            <div style="color: #909399; font-size: 12px;">{{ scope.row.points }}积分</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="支付平台" align="center" prop="paymentPlatform" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.paymentPlatform === 'alipay'" type="primary" size="small">支付宝</el-tag>
          <el-tag v-else-if="scope.row.paymentPlatform === 'wechat'" type="success" size="small">微信</el-tag>
          <span v-else>{{ scope.row.paymentPlatform }}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付状态" align="center" prop="paymentStatus" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.paymentStatus === 0" type="warning" size="small">待支付</el-tag>
          <el-tag v-else-if="scope.row.paymentStatus === 1" type="success" size="small">已支付</el-tag>
          <el-tag v-else-if="scope.row.paymentStatus === 2" type="info" size="small">已关闭</el-tag>
          <el-tag v-else-if="scope.row.paymentStatus === 3" type="danger" size="small">已退款</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="支付时间" align="center" prop="paymentTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.paymentTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createdAt" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:paymentOrders:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:paymentOrders:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改支付订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-tabs v-model="activeTab" type="border-card">
          <!-- 订单信息 -->
          <el-tab-pane label="订单信息" name="order">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="订单号" prop="orderId">
                  <el-input v-model="form.orderId" placeholder="系统自动生成" :disabled="form.orderId !== null && form.orderId !== ''" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="用户ID" prop="userId">
                  <el-input v-model="form.userId" placeholder="请输入用户ID" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="支付平台" prop="paymentPlatform">
                  <el-select v-model="form.paymentPlatform" placeholder="请选择平台" style="width: 100%">
                    <el-option label="支付宝" value="alipay" />
                    <el-option label="微信支付" value="wechat" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="订单标题" prop="orderTitle">
                  <el-input v-model="form.orderTitle" placeholder="请输入订单标题" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="订单描述" prop="orderDescription">
                  <el-input 
                    v-model="form.orderDescription" 
                    type="textarea"
                    :rows="3"
                    placeholder="请输入订单描述"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="支付金额（元）" prop="amount">
                  <el-input-number v-model="form.amount" :precision="2" :step="0.01" :min="0" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="积分数量" prop="points">
                  <el-input-number v-model="form.points" :min="0" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <!-- 支付信息 -->
          <el-tab-pane label="支付信息" name="payment">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="支付状态" prop="paymentStatus">
                  <el-select v-model="form.paymentStatus" placeholder="请选择状态" style="width: 100%">
                    <el-option label="待支付" :value="0" />
                    <el-option label="已支付" :value="1" />
                    <el-option label="已关闭" :value="2" />
                    <el-option label="已退款" :value="3" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="支付完成时间" prop="paymentTime">
                  <el-date-picker clearable style="width: 100%"
                    v-model="form.paymentTime"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="请选择支付完成时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="支付宝交易号" prop="alipayTradeNo">
                  <el-input v-model="form.alipayTradeNo" placeholder="请输入支付宝交易号" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="支付宝应用ID" prop="alipayAppId">
                  <el-input v-model="form.alipayAppId" placeholder="请输入支付宝应用ID" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="商户订单号" prop="alipayOutTradeNo">
                  <el-input v-model="form.alipayOutTradeNo" placeholder="请输入支付宝商户订单号" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="回调通知时间" prop="notifyTime">
                  <el-date-picker clearable style="width: 100%"
                    v-model="form.notifyTime"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="请选择回调通知时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="订单过期时间" prop="expireTime">
                  <el-date-picker clearable style="width: 100%"
                    v-model="form.expireTime"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="请选择订单过期时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="回调通知数据" prop="notifyData">
                  <el-input 
                    v-model="form.notifyData" 
                    type="textarea"
                    :rows="5"
                    placeholder='请输入JSON格式的回调通知数据'
                  />
                  <span class="form-tip">* 请输入合法的JSON格式数据</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <!-- 退款信息 -->
          <el-tab-pane label="退款信息" name="refund">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="退款时间" prop="refundTime">
                  <el-date-picker clearable style="width: 100%"
                    v-model="form.refundTime"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="请选择退款时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="退款金额（元）" prop="refundAmount">
                  <el-input-number v-model="form.refundAmount" :precision="2" :step="0.01" :min="0" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="退款原因" prop="refundReason">
                  <el-input 
                    v-model="form.refundReason" 
                    type="textarea"
                    :rows="4"
                    placeholder="请输入退款原因"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="操作员" prop="operator">
                  <el-input v-model="form.operator" placeholder="请输入操作员姓名" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <!-- 客户端信息 -->
          <el-tab-pane label="客户端信息" name="client">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="客户端IP" prop="clientIp">
                  <el-input v-model="form.clientIp" placeholder="请输入客户端IP地址" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="User Agent" prop="userAgent">
                  <el-input 
                    v-model="form.userAgent" 
                    type="textarea"
                    :rows="3"
                    placeholder="请输入客户端User Agent信息"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <!-- 扩展信息 -->
          <el-tab-pane label="扩展信息" name="extra">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="扩展数据" prop="extraData">
                  <el-input 
                    v-model="form.extraData" 
                    type="textarea"
                    :rows="8"
                    placeholder='请输入JSON格式的扩展数据'
                  />
                  <span class="form-tip">* 请输入合法的JSON格式数据</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPaymentOrders, getPaymentOrders, delPaymentOrders, addPaymentOrders, updatePaymentOrders } from "@/api/system/paymentOrders";

export default {
  name: "PaymentOrders",
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      paymentOrdersList: [],
      title: "",
      open: false,
      activeTab: 'order',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderId: null,
        userId: null,
        amount: null,
        points: null,
        orderTitle: null,
        orderDescription: null,
        paymentPlatform: null,
        alipayTradeNo: null,
        alipayAppId: null,
        alipayOutTradeNo: null,
        paymentStatus: null,
        notifyData: null,
        notifyTime: null,
        clientIp: null,
        userAgent: null,
        expireTime: null,
        paymentTime: null,
        refundTime: null,
        refundAmount: null,
        refundReason: null,
        operator: null,
        extraData: null,
        createdAt: null,
        updatedAt: null
      },
      form: {},
      rules: {
        orderId: [
          { required: true, message: "订单号不能为空", trigger: "blur" }
        ],
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ],
        amount: [
          { required: true, message: "支付金额不能为空", trigger: "blur" }
        ],
        points: [
          { required: true, message: "购买积分数量不能为空", trigger: "blur" }
        ],
        orderTitle: [
          { required: true, message: "订单标题不能为空", trigger: "blur" }
        ],
        paymentPlatform: [
          { required: true, message: "支付平台不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      listPaymentOrders(this.queryParams).then(response => {
        this.paymentOrdersList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        orderId: null,
        userId: null,
        amount: 0,
        points: 0,
        orderTitle: null,
        orderDescription: null,
        paymentPlatform: null,
        alipayTradeNo: null,
        alipayAppId: null,
        alipayOutTradeNo: null,
        paymentStatus: 0,
        notifyData: null,
        notifyTime: null,
        clientIp: null,
        userAgent: null,
        expireTime: null,
        paymentTime: null,
        refundTime: null,
        refundAmount: null,
        refundReason: null,
        operator: null,
        extraData: null,
        createdAt: null,
        updatedAt: null
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset();
      this.activeTab = 'order';
      this.open = true;
      this.title = "添加支付订单";
    },
    handleUpdate(row) {
      this.reset();
      this.activeTab = 'order';
      const orderId = row.orderId || this.ids
      getPaymentOrders(orderId).then(response => {
        this.form = response.data;
        
        // 处理JSON字段
        const jsonFields = ['notifyData', 'extraData'];
        for (const field of jsonFields) {
          if (this.form[field] && typeof this.form[field] === 'object') {
            this.form[field] = JSON.stringify(this.form[field], null, 2);
          }
        }
        
        this.open = true;
        this.title = "查看支付订单详情";
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const submitForm = JSON.parse(JSON.stringify(this.form));
          
          // 处理JSON字段
          const jsonFields = ['notifyData', 'extraData'];
          for (const field of jsonFields) {
            if (submitForm[field] && typeof submitForm[field] === 'string') {
              try {
                submitForm[field] = submitForm[field].trim() 
                  ? JSON.parse(submitForm[field]) 
                  : null;
              } catch (e) {
                this.$modal.msgError(`${field}字段JSON格式不正确`);
                return;
              }
            }
          }
          
          if (submitForm.orderId != null && submitForm.orderId !== '') {
            updatePaymentOrders(submitForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPaymentOrders(submitForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDelete(row) {
      const orderIds = row.orderId || this.ids;
      this.$modal.confirm('是否确认删除支付订单编号为"' + orderIds + '"的数据项？').then(function() {
        return delPaymentOrders(orderIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleExport() {
      this.download('system/paymentOrders/export', {
        ...this.queryParams
      }, `paymentOrders_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.form-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
  margin-top: 4px;
  display: block;
}

::v-deep .el-tabs--border-card {
  box-shadow: none;
}

::v-deep .el-tabs__content {
  padding: 20px;
}
</style>
